package com.duoqin.syncassistant;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Utils {
    private static final String TAG = "duoqin_Util";
    private static final char[] hexArray = "0123456789abcdef".toCharArray();

    public static final String LOCAL_CONTACT_ACCOUNT_NAME = "Phone";
    public static final String LOCAL_CONTACT_ACCOUNT_TYPE = "sprd.com.android.account.phone";

    private static final String Algorithm = "AES/CBC/PKCS5Padding";
    private static final String IV = "0000000000000000";
    private static final String KEY = "duoqin8888keapaw";

    public static String aesEncrypt(byte[] value) throws NoSuchPaddingException, NoSuchAlgorithmException
            , UnsupportedEncodingException, InvalidAlgorithmParameterException, InvalidKeyException
            , BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(Algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, aesKeyToSpec(), new IvParameterSpec(IV.getBytes("UTF-8")));
        return Base64.encodeToString(cipher.doFinal(), Base64.DEFAULT);
    }

    public static String aesDecrypt(byte[] encryptedValue) throws NoSuchPaddingException, NoSuchAlgorithmException
            , UnsupportedEncodingException, InvalidAlgorithmParameterException
            , InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(Algorithm);
        cipher.init(Cipher.DECRYPT_MODE, aesKeyToSpec(), new IvParameterSpec(IV.getBytes("UTF-8")));
        System.out.println(encryptedValue.length);
        byte[] result =  cipher.doFinal(encryptedValue);
        return new String(result,"UTF-8");
    }

    private static SecretKeySpec aesKeyToSpec() throws UnsupportedEncodingException {
        byte[] keyBytes = KEY.getBytes("UTF-8");
        return new SecretKeySpec(keyBytes, "AES");
    }

    public static String md5(byte[] bytes) {
        StringBuffer sb = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte b[] = md.digest();
            int d;
            for (int i = 0; i < b.length; i++) {
                d = b[i];
                if (d < 0) {
                    d = b[i] & 0xff;
                    // 与上一行效果等同
                    // i += 256;
                }
                if (d < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(d));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();
        return sb.toString();
    }

    public static String getStringFromFile (String filePath) throws Exception {
        File fl = new File(filePath);
        FileInputStream fin = new FileInputStream(fl);
        String ret = convertStreamToString(fin);
        //Make sure you close all streams.
        fin.close();
        return ret;
    }

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    public static String timestamp() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static String checksum_HmacSHA1(String content, String key) {
        return checksum_hmac(content, key, "HmacSHA1");
    }

    public static String checksum_HmacSHA256(String content, String key) {
        return checksum_hmac(content, key, "HmacSHA256");
    }

    public static String checksum_hmac(String content, String key, String algorithm) {
        try {
            Mac mac = Mac.getInstance(algorithm);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
            mac.init(keySpec);
            String checksum = bytesToHex(mac.doFinal(content.getBytes()));
            return checksum;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String md5sum(byte[] content, int offset, int len) {
        try {
            Log.w(TAG, "length: " + content.length);
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content, offset, len);

            byte[] result = digest.digest();
            String checksum = bytesToHex(result);
            return checksum;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getString(String string){
        if(TextUtils.isEmpty(string)){
            return "";
        }
        return string;
    }

    public static boolean isNetWorkAvilable(Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            Log.w(TAG, "couldn't get connectivity manager");
        } else {
            NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
            if (networkInfos != null) {
                for (int i = 0, count = networkInfos.length; i < count; i++) {
                    if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isAppInstalled(Context context, String packageName){
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
